package com.yst.common.utils.oss;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yst.common.config.OssConfig;
import com.yst.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

@Service
@Slf4j
public class AliyunOSSUtil {
    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private OSSClient ossClient;

    /**
     * 上传
     *
     * @param file
     * @return
     */
    public String upload(File file) throws IOException {
        return upload(file, null);
    }

    /**
     * 上传
     *
     * @param file
     * @return
     */
    public String upload(File file, String fileName) throws IOException {
        try (InputStream inputStream = new FileInputStream(file)) {
            fileName = StringUtils.isBlank(fileName) ? file.getName().replaceAll(" ", "") : fileName;
           // fileName = URLEncoder.encode(fileName, "UTF-8");
            //创建文件路径
            String fileUrl = ossConfig.getDir() + "/" + fileName;
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(ossConfig.getBucketname(), fileUrl, inputStream));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(ossConfig.getBucketname(), CannedAccessControlList.PublicRead);
            if (null != result) {
                log.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return ossConfig.getFilehost() + "/" + fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        }
        return null;
    }


    /**
     * 通过文件流上传
     *
     * @return
     */
    public String upload(InputStream inputStream, String filename) {
        try {
            String fileName = filename.replaceAll(" ", "");
            //创建文件路径
            String fileUrl = ossConfig.getDir() + "/" + fileName;
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(ossConfig.getBucketname(), fileUrl, inputStream));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(ossConfig.getBucketname(), CannedAccessControlList.PublicRead);
            if (null != result) {
                log.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return ossConfig.getFilehost() + "/" + fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        }
        return null;
    }


    /**
     * 删除
     *
     * @param fileKey
     * @return
     */
    public String delete(String fileKey) {
        try {

            if (!ossClient.doesBucketExist(ossConfig.getBucketname())) {
                log.info("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            } else {
                log.info("==============>开始删除Object");
                ossClient.deleteObject(ossConfig.getBucketname(), fileKey);
                log.info("==============>Object删除成功：" + fileKey);
                return "==============>Object删除成功：" + fileKey;
            }
        } catch (Exception ex) {
            log.info("删除Object失败", ex);
            return "删除Object失败";
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteOSSFile(String filePath) {
        String newFilePath = ossConfig.getDir() + "/" + filePath;
        ossClient.deleteObject(ossConfig.getBucketname(), newFilePath);
    }


    /**
     * 下载OSS上的文件
     *
     * @param outputStream
     * @param filePath     完整文件路径
     */
    public void downloadFile(OutputStream outputStream, String filePath) {
        OSSObject ossObject = ossClient.getObject(ossConfig.getBucketname(), filePath);
        // 读取文件内容
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

        BufferedOutputStream out = new BufferedOutputStream(outputStream);
        byte[] buffer = new byte[1024];
        int length = 0;
        try {
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (ossObject != null) {
                ossObject.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
